import React, { useState, useEffect, useRef, useMemo } from "react";
import { message, Button, Table, Pagination, Space } from "antd";
import { Panel, FormSelect, UploadModal } from "@/components";
import { useEventListener } from "ahooks";
import dictionary, { echartTypes } from "@/config/character";
import ajax from "@/services";
import "./index.scss";

import EditModal from "./EditModal";
import EditModal_HeatMap from "./EditModal_HeatMap";

/**
 * @description 数据导入
 **/
export default function UpData(props) {
  const [formData, setFormData] = useState({
    chart_type: "",
    is_default: "1",
    pn: 1,
    page_size: dictionary.pageSizeOptions[0],
  });

  const searchForm = useRef({
    defaultForm: { ...formData },
    form: { ...formData },
    ajaxpnLoading: false,
    defaultResultData: {
      total: 0,
      data: [],
    },
  });
  const searchData = searchForm.current;

  const [ajaxLoading, setAjaxLoading] = useState(false);
  const [resultData, setResultData] = useState(searchData.defaultResultData);
  const [scrollHeight, setScrollHeight] = useState(450);

  // 上传
  const [visible, setVisible] = useState(false);

  // 编辑
  const [modalConfig, setModalConfig] = useState({
    visible: false,
    modalData: {},
  });

  // 获取列表数据
  const getList = (data = formData, isFirst) => {
    setAjaxLoading(true);
    ajax
      .getFileList(data)
      .then(
        (res) => {
          if (res.data.length) {
            setResultData(res);
          } else {
            setResultData(searchData.defaultResultData);
          }
        },
        (err) => {
          console.log(err);
          setResultData(searchData.defaultResultData);
        }
      )
      .finally(() => {
        searchData.ajaxpnLoading = false;
        setAjaxLoading(false);
        isFirst && handleResize();
      });
  };

  // 表单change
  const handleChange = (v, option) => {
    setFormData({ ...formData, chart_type: option.children });
    searchData.form.chart_type = option.children;
  };

  // 搜索
  const search = (flag) => {
    console.log('searchData', searchData);
    if (!searchData.ajaxpnLoading) {
      setResultData(searchData.defaultResultData);
    }
    if (!flag) {
      searchData.form.pn = 1;
    }
    getList(searchData.form);
    setFormData({ ...searchData.form });
  };

  //重置
  const handleReset = () => {
    setFormData(searchData.defaultForm);
    searchData.form = { ...searchData.defaultForm };
  };

  const columns = [
    {
      title: "序号",
      dataIndex: "index",
      align: "center",
      width: 90,
      render: (val, row, index) => {
        return <>{index + 1 + formData.page_size * (formData.pn - 1)}</>;
      },
    },
    {
      title: "文件名称",
      dataIndex: "file_name",
      align: "center",
    },
    {
      title: "图表类型",
      dataIndex: "chart_type",
      align: "center",
    },
    {
      title: "X轴",
      dataIndex: "x_title",
      align: "center",
    },
    {
      title: "Y轴",
      dataIndex: "y_title",
      align: "center",
    },
    {
      title: "创建时间",
      dataIndex: "create_time",
      align: "center",
    },
    {
      title: "操作",
      align: "center",
      width: 140,
      render: (row) => {
        return (
          <Space>
            <Button
              size="small"
              type="link"
              onClick={() => setModalConfig({ visible: true, modalData: row })}
            >
              编辑
            </Button>
            <Button
              size="small"
              type="link"
              target="_blank"
              href={row.file_path}
            >
              下载文件
            </Button>
          </Space>
        );
      },
    },
  ];

  // 分页
  const paginationProps = {
    className: "pagination-box",
    showQuickJumper: true,
    showSizeChanger: true,
    hideOnSinglePage: true,
    current: parseInt(formData.pn),
    pageSize: parseInt(formData.page_size),
    total: resultData.total,
    showTotal: (total) => `共 ${total} 条`,
    pageSizeOptions: dictionary.pageSizeOptions,
    onChange: (pn, page_size) => {
      const isPageSize = searchData.form.page_size === page_size;
      if (isPageSize) {
        searchData.form.pn = pn;
      } else {
        searchData.form.page_size = page_size;
        searchData.form.pn = 1;
      }
      searchData.ajaxpnLoading = true;
      search(isPageSize);
    },
  };

  const handleResize = () => {
    const tableWarp = document.querySelector(".result-table");
    if (tableWarp) {
      let tableHight = tableWarp.clientHeight - 56;
      setScrollHeight(tableHight);
    }
  };

  // 关闭上传弹窗
  const handleCloseUploadModal = (flag) => {
    setVisible(false);
    if (flag) {
      search();
    }
  };

  //编辑弹窗
  const editProps = useMemo(() => {
    return {
      ...modalConfig,
      onCancel: (flag) => {
        setModalConfig({ visible: false, modalData: {} });
        console.log(flag);
        flag && search();
      },
    };
  }, [modalConfig]);

  useEventListener("resize", handleResize, { target: window });
  useEffect(() => {
    getList(formData, true);
  }, []);

  return (
    <div className="up-data-page">
      <Panel className="form-group">
        <FormSelect
          className="form-item"
          admLabel="图表类型"
          labelPosition="left"
          value={formData.chart_type}
          options={echartTypes}
          onChange={handleChange}
        />
        <div className="btn-group">
          <Button type="primary" loading={ajaxLoading} onClick={() => search()}>
            检索
          </Button>
          <Button onClick={handleReset}>重置</Button>
        </div>
      </Panel>
      <Panel className="result-body">
        <div className="result-header">
          <span className="total">
            {ajaxLoading && !searchData.ajaxpnLoading ? (
              "加载中..."
            ) : (
              <>
                共<em> {resultData.total || "0"} </em> 条数据
              </>
            )}
          </span>
          <Button
            className="add-btn"
            type="primary"
            onClick={() => setVisible(true)}
          >
            上传数据
          </Button>
        </div>
        <div className="result-table">
          <Table
            scroll={{ y: scrollHeight }}
            rowKey={(row) => row.id}
            columns={columns}
            dataSource={resultData.data}
            bordered
            loading={ajaxLoading}
            pagination={false}
          />
        </div>
        {resultData.total > 0 && <Pagination {...paginationProps} />}
      </Panel>
      <UploadModal
        visible={visible}
        chartTypeOptions={echartTypes}
        onCancel={handleCloseUploadModal}
      />
      {
        editProps.modalData.chart_type === '地图热力图' ? <EditModal_HeatMap {...editProps} /> : <EditModal {...editProps} />
      }
    </div>
  );
}
